//------------------------------------------------------------------------------
// JAVA    : ezCall_Screen
//
// Made by : Cho HanCheol.
// Date    : 2009. 9. 6.
//------------------------------------------------------------------------------

// 0.6.0 
//   - 컴파일러 최신 버젼으로 변경
//   - OS 5.0 이상 지원


package ezCall;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import javax.microedition.pim.Contact;
import javax.microedition.pim.ContactList;
import javax.microedition.pim.PIM;
import javax.microedition.pim.PIMException;




import net.rim.blackberry.api.invoke.Invoke;
import net.rim.blackberry.api.invoke.PhoneArguments;
import net.rim.blackberry.api.pdap.BlackBerryContact;
import net.rim.device.api.collection.ReadableList;
import net.rim.device.api.i18n.Locale;
import net.rim.device.api.io.Base64InputStream;
import net.rim.device.api.math.Fixed32;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.system.KeyListener;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Keypad;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.UiEngine;
import net.rim.device.api.ui.XYRect;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.KeywordFilterField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.component.Status;
import net.rim.device.api.ui.component.TextField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.PopupScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.util.CharacterUtilities;


// chcbaram.ezcall
// 0x805c524a0059d52dL

//------------------------------------------------------------------------------
//CLASS : ezCall_Screen
//
//WORK : 
//------------------------------------------------------------------------------
public class ezCall_Screen extends MainScreen  implements ListFieldCallback 
{

	private Contact_DB         _Contact_DB;      
	private Contact_ListField  _Contact_ListField;
	
	private HorizontalFieldManager _Title_FieldManager;
	private TitleInfo_LabelField   _TitleInfo_LabelField;
	
    private MenuItem_Call   _MenuItem_Call;    
    private MenuItem_About  _MenuItem_About;
    private MenuItem_Option _MenuItem_Option;  
    private Find_Field      _ContactList_FindField;
    private String_Cho      _String_Cho;
    
    private String _String_SelectedListPhoneNumber;

    private FindField_Text  _FindField_Text;
    
    final int ListRowMargin = 4;

    boolean _AfterCalling;
    
    
    private static PersistentObject _persist;
    private static Option_Model     _Option_Model;

    private String _Top_Str;
    
    private int KeyCodeStatus;
    private int KeyCodeWith;
 
    int  KeyPressedTime_Prev;  
    char KeyPressedCode_Prev;
    
    static 
    {
    	if( DebugMode.SaveMode )
    	{
	        _persist = PersistentStore.getPersistentObject( 0x805c524a0059d52dL ); // chcbaram.ezcall
	        
	        synchronized( _persist ) 
	        {
	            if( _persist.getContents() == null ) 
	            {
	                _persist.setContents( new Option_Model() );
	                _persist.commit();
	                
	            }
	        }
	        _Option_Model = (Option_Model) _persist.getContents();  
    	}
    }
    
    
	//--------------------------------------------------------------------------
	// 함수 : ezCall_Screen
	// 기능 : 
	//--------------------------------------------------------------------------
    public ezCall_Screen()
    {
    	
    	_AfterCalling = false;
    	
    	 _FindField_Text = new FindField_Text();
    	 
    	//-- 주소 리스트 생성
        //
    	_Contact_DB = new Contact_DB();
        
    	_Contact_DB.Set_Screen(this);
    	
    	_FindField_Text.Set_Text("");
        
    	/*
    	_Contact_DB.Search( _FindField_Text );
        if( _Contact_DB.isContactLoaded() == false )
        {
        	System.exit(0);        
        }
        */
    	
    	
        //-- FIND 필드
        _Title_FieldManager = new HorizontalFieldManager();
    	

        _ContactList_FindField = new Find_Field("Find: ");
        _ContactList_FindField.Set_Screen(this);
        
        _TitleInfo_LabelField  = new TitleInfo_LabelField();
        
        
        _Title_FieldManager.add(_ContactList_FindField);
        _Title_FieldManager.add(_TitleInfo_LabelField);

        setTitle( _Title_FieldManager );
        
    	_Contact_ListField = new Contact_ListField();
    	_Contact_ListField.setCallback(this);        
    	_Contact_ListField.setSize(_Contact_DB.Get_MaxSize());    
    	
    	
    	add(_Contact_ListField);
    	Contact_ListAdjust();
    	
    	
    	
        //-- 메뉴 생성
        //
    	
    	// 기본 Close 메뉴 삭제
    	setDefaultClose(false);
    	
        _MenuItem_Call = new MenuItem_Call();
        _MenuItem_About = new MenuItem_About();
        _MenuItem_Option = new MenuItem_Option();
        
        //-- 메뉴 추가
        //
        //addMenuItem(_MenuItem_Call);
        addMenuItem(_MenuItem_About );
        //addMenuItem(new MenuItem_ReloadDB() );
        addMenuItem( _MenuItem_Option );
        
        addMenuItem(MenuItem.separator(_MenuItem_About.getOrdinal() + 1));
        addMenuItem( new MenuItem_Close() );
        
        _String_SelectedListPhoneNumber = new String();
        
        _Contact_DB.Set_OptionModel(_Option_Model);
        _Contact_DB.start();
        
        
        KeyPressedTime_Prev = 0;
        KeyPressedCode_Prev = 0;
    }
    
    
    public void Contact_ListAdjust()
    {
    	Font _Font;    	
    	_Font = this.getFont();
    	
    	// 리스트 높이 조절
    	//
    	if( _Option_Model.Get_Photo_View() )
    	{
    		_Contact_ListField.setRowHeight( _Font.getHeight()*2 + ListRowMargin*2  );
    	}
    	else
    	{
    		_Contact_ListField.setRowHeight( _Font.getHeight() + ListRowMargin  );
    	}
    	
    }
    
    
    public void ReloadDB()
    {
    	_Contact_DB.ReloadDB();
    }
    
    
    
    private class Contact_ListField extends ListField
    {
        public Contact_ListField( )
        {
        	super();
        }
        
    }
    private class TitleInfo_LabelField extends RichTextField
    {


        // Contructor
        public TitleInfo_LabelField( )
        {    	
        	//super("", "", 20, NON_FOCUSABLE|NO_LEARNING|NO_NEWLINE| EditField.NO_EDIT_MODE_INPUT|EditField.FIELD_RIGHT );
        	super( NO_EDIT_MODE_INPUT | NO_NEWLINE | NON_FOCUSABLE | TEXT_ALIGN_RIGHT );
        }
    	
    	/*
        protected void layout(int width, int height )
        {
        	super.layout(getPreferredWidth(), getPreferredHeight());
        	
        	//setExtent(getPreferredWidth(), getPreferredHeight() );
        } 
        */       
        /*        
        public int getPreferredWidth()
        {
        	return Graphics.getScreenWidth()/2;
        }
        */
        protected void paint(Graphics graphics)
        {            
            super.paint(graphics);
            
            //graphics.drawText(_TitleInfo_Str, 0, _TitleInfo_Str.length(),0,0, graphics.RIGHT , graphics.getScreenWidth() );        
            //graphics.drawRect(0, 0, getPreferredWidth()-1, getPreferredHeight() );
        }    
    }
    
    protected boolean navigationMovement(int dx, int dy, int status, int time )
    {
    	
    	// RIGHT
    	if( dx > 0 && _Contact_ListField.getSize() > 0 )
    	{
    		Popup_SelectedListPhoneNumber();
    	}
    	else
    	if( dx < 0 ) // LEFT
    	{
    		/*
    		if( _ContactList_FindField.getText().length() == 0 )
    		{
    			
    		}
    		*/
    	}
		
    	return super.navigationMovement(dx, dy, status, time);
    }

    
    //-- 리스트에서 우측으로 트랙볼 이동시 전화번호 리스트 출력
    //
    public void Popup_SelectedListPhoneNumber()
    {
    	String[] PhoneNumberArray;
    	String[] PhoneNumberHeaderArray;
    	
		//String[] MenuStr;
		int SelectedIndex;
		
		SelectedIndex = _Contact_ListField.getSelectedIndex();
		
		
		BlackBerryContact c = (BlackBerryContact)_Contact_DB.Get_ItemObjectFromIndex(SelectedIndex);
		
		Contact_PhoneNum _PhoneNum = new Contact_PhoneNum();
		_PhoneNum.Set_Contact(c);

		if( _PhoneNum.Get_ContactLoadedFlag() )
		{
			PhoneNumberArray = _PhoneNum.Get_PhoneNumberArray();	
			PhoneNumberHeaderArray = _PhoneNum.Get_PhoneNumberNameArray();
			PhoneList_PopupScreen _MyPopup = new PhoneList_PopupScreen( PhoneNumberHeaderArray, PhoneNumberArray );		
			//UiApplication.getUiApplication().pushScreen( _MyPopup );
			_MyPopup.Set_OptionModel(_Option_Model);
			UiApplication.getUiApplication().pushModalScreen( _MyPopup );
			
			_AfterCalling = _MyPopup._AfterCalling;
			
			//
			//
			if( _MyPopup._Action )
			{
    			if( _Option_Model.Get_ClearText_AfterCall() )
    			{
    				_ContactList_FindField.setText("");
    				_FindField_Text.Set_Text( "" );
    			}
			}
		}
    }
    
    

    public boolean Popup_SelectedListEmail()
    {
    	boolean  Ret = false;
    	String[] PhoneNumberArray;
    	String[] PhoneNumberHeaderArray;
    	
		int SelectedIndex;
		
		SelectedIndex = _Contact_ListField.getSelectedIndex();
		
		BlackBerryContact c = (BlackBerryContact)_Contact_DB.Get_ItemObjectFromIndex(SelectedIndex);
		
		Contact_PhoneNum _PhoneNum = new Contact_PhoneNum();
		_PhoneNum.Set_ContactEmail(c);
		
		if( _PhoneNum.Get_ContactLoadedFlag() )
		{
			PhoneNumberArray = _PhoneNum.Get_PhoneNumberArray();	
			PhoneNumberHeaderArray = _PhoneNum.Get_PhoneNumberNameArray();
			PhoneList_PopupScreen _MyPopup = new PhoneList_PopupScreen( PhoneNumberHeaderArray, PhoneNumberArray );		

			_MyPopup.Set_OptionModel(_Option_Model);
			UiApplication.getUiApplication().pushModalScreen( _MyPopup );
			
			_AfterCalling = _MyPopup._AfterCalling;
			if( _MyPopup._AfterSMS ) Ret = true;
			
			
			//
			//
			if( _MyPopup._Action )
			{
    			if( _Option_Model.Get_ClearText_AfterCall() )
    			{
    				_ContactList_FindField.setText("");
    				_FindField_Text.Set_Text( "" );
    			}
			}
		}

		return Ret;
    }    

    
    //-- 리스트에서 우측으로 트랙볼 이동시 전화번호 리스트 출력
    //
    public String Popup_FindOption()
    {
    	String RetStr = new String();
    	
    	String[] MenuArray = { ": Find PhoneNumber", 
    			               ": Find Name Only",
                               ": Find Company Only",
                               ": Find Note",
                               ": Find Category",
                               };
                               
	
    	
    	
    	String[] OptionArray = { "#",
    			                 "+",
                                 ";",
                                 "*",
                                 "-"
    			                 };
    			                 

    	
    	RetStr = "";
    	
		FindList_PopupScreen _MyPopup = new FindList_PopupScreen( OptionArray, MenuArray );
		UiApplication.getUiApplication().pushModalScreen( _MyPopup );
		
		if( _MyPopup.Get_SavedOK() )
		{
			RetStr = OptionArray[_MyPopup.Get_SavedSelectedIndex() ];
		}
		
		return RetStr;
    }    
    
    
    
    
    
	public boolean keyChar(char key, int status, int time)
	{	
		boolean ret;
		int     KeyCode;
		

		//KeyCode = Keypad.getKeyCode(key, status);
		//Dialog.alert(Integer.toHexString( KeyCode )); 

		
		if( _Option_Model.Get_Support9100() == true )
		{
			// 300ms 이하로 키입력시 9100 해당키 입력
			//
			if( (time-KeyPressedTime_Prev) < 300 && (time-KeyPressedTime_Prev) > -300 )
			{
				// 한글/영문 일때만 앞글자를 지운다.
				//
				if( String_Cho.is_Char( key ) == 1 )
				{
					_ContactList_FindField.Remove_LastChar();
				}
				
				key = String_Cho.Get_KeyWithAlt( key );
			}
		}
		
		
		// 전화번호 검색시에는 누른 키를 숫자로 변환
		//
		if( _FindField_Text.Get_FindMode() == FindField_Text.FIND_MODE_PHONE_NUMBER )
		{
			char KeyNum = Get_NumKeypadPressed( key, status );
			//UiApplication.getUiApplication().pushGlobalScreen(_MyPopup, 1, UiApplication.GLOBAL_QUEUE   );
			if( KeyNum > 0 ) 
				key = KeyNum;
		}
		else
		{
			// 공백을 누르면 영/한을 바꾼다.
			if( Characters.SPACE == key )
			{
				if( _ContactList_FindField.getText().length() > 0 )
				{
					String FindStr = String_Cho.Get_ToggledStr( _ContactList_FindField.getText() );
						
					_ContactList_FindField.setText(FindStr);
					_FindField_Text.Set_Text( _ContactList_FindField.getText() );
					
					
					ret = _Contact_DB.Search( _FindField_Text );
					
			    	_Contact_ListField.setSize(_Contact_DB.Get_MaxSize());  
					
			    	// 검색 결과가 없으면 리스트 Draw가 없으므로 여기서 클리어.
					if( _Contact_DB.Get_MaxSize() == 0 )
					{
						_TitleInfo_LabelField.setText("");
					}
				}
				return true;
			}
			
			
			if( _Option_Model.Get_DefaultInputMode() == Option_Model.DEFAULT_INPUT_MODE_KOREAN )
			{
				key = String_Cho.Get_EnglishToKorean( key );
				
			}
			else
			if( _Option_Model.Get_DefaultInputMode() == Option_Model.DEFAULT_INPUT_MODE_ENGLISH)
			{
				key = String_Cho.Get_KoreanToEnglish( key );
			}
			
		}
			
		
		
		// 취소키 누르면 입력창에 글자 있으면 삭제/ 없으면 백그라운드 실행
		//
		ret = _ContactList_FindField.keyChar(key, status, time);
		if( ret )
		{
			_FindField_Text.Set_FindMode(FindField_Text.FIND_MODE_NAME_COMPANY);
			
			return true; 
		}
		
		
		
		
		_FindField_Text.Set_Text( _ContactList_FindField.getText() );
		
		// 디버그 코드
		//_ContactList_FindField.setText( Integer.toString(time - KeyPressedTime_Prev) );
				
		
		if( _FindField_Text.isValidText() == false &&  _FindField_Text.Get_StrSize() > 0 )
		{
			return true;
		}
		
		
		ret = _Contact_DB.Search( _FindField_Text );
		
    	_Contact_ListField.setSize(_Contact_DB.Get_MaxSize());  
		
    	// 검색 결과가 없으면 리스트 Draw가 없으므로 여기서 클리어.
		if( _Contact_DB.Get_MaxSize() == 0 )
		{
			_TitleInfo_LabelField.setText("");
		}
	
    	
		KeyPressedCode_Prev = key; 
		KeyPressedTime_Prev = time;

		
		return super.keyChar(key, status, time);		
	}
	

	
	
	public void Show_AllPhoneList()
	{
		_FindField_Text.Set_Text( "" );
		
		_Contact_DB.Search( _FindField_Text );
		
    	_Contact_ListField.setSize(_Contact_DB.Get_MaxSize());  
	}
	
	
	public boolean keyDown(int keycode, int time)
	{
		final int SYMBOL_KEYCODE = 0x7F;

    	//Dialog.alert( Integer.toHexString( Keypad.status(keycode)));

		// 다른키랑 눌렸는지 검사.
		KeyCodeStatus = Keypad.status(keycode);
		KeyCodeWith   = Keypad.key(keycode);
		
		switch (Keypad.key(keycode)) 
		{
        case Keypad.KEY_END:        	
            break;
        case Keypad.KEY_SEND: // 통화 키 
        	
        	if( Call_SelectedNumber() == false )
        	{
        		Dialog.alert("Invalid Phone Number");
        		break;
        	}
        	
        	UiApplication.getUiApplication().requestBackground(); 
        	return true;            

        case SYMBOL_KEYCODE: // 심볼키        		
        	
    		String Str = new String(); 		
    		
    		Str = Popup_FindOption();
    		
    		if( Str.length() > 0 )
    		{
    			Str = _ContactList_FindField.getText() + Str;    			
	    		_ContactList_FindField.setText(Str);	
	    		
	    		_FindField_Text.Set_Text( _ContactList_FindField.getText() );
    		}
    		
        	break;
        	
        case Keypad.KEY_ENTER:
        	
        	//Dialog.alert( Integer.toHexString( Keypad.status(keycode)));
        	
        	// 순수하게 엔터키만 눌렀을때 실행..
        	if( Keypad.status(keycode) == 0 )
        	{
	    		String OptStr = _Option_Model.Get_Field( Option_Model.MAIN_SCREEN_ENTER_FUNC );
	    		
	    		boolean Ret = Action_FromString( OptStr );
	    		
	    		if( Ret ) return true;
        	}
        	
        	break;
		
		}

		
		
		return  super.keyDown(keycode, time);
	}		
	

	boolean isNumKeypadPressed( char key, int status )
	{
		int     KeyCode;		
		//                               0     1     2    3     4      5    6     7     8     9    
		char[]  NumKeypadCodeTable = { 0x30, 0x57, 0x45, 0x52, 0x53, 0x44, 0x46, 0x5A, 0x58, 0x43 };
		
		
		KeyCode = Keypad.getKeyCode(key, status);
		
		for( int i=0; i<10; i++ )
		{
			if( NumKeypadCodeTable[i] == KeyCode ) return true;
		}
		
		return false;
	}

	char Get_NumKeypadPressed( char key, int status )
	{
		int     KeyCode;		
		//                               0     1     2    3     4      5    6     7     8     9    
		char[]  NumKeypadCodeTable = { 0x30, 0x57, 0x45, 0x52, 0x53, 0x44, 0x46, 0x5A, 0x58, 0x43 };
		char[]  NumKeypadCharTable = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		
		KeyCode = Keypad.getKeyCode(key, status);
		
		for( int i=0; i<10; i++ )
		{
			if( NumKeypadCodeTable[i] == KeyCode )
			{
				return NumKeypadCharTable[i];
			}
		}
		
		return 0;

	
	}	
    
	protected boolean navigationClick(int status, int time)
	{
		String OptStr = _Option_Model.Get_Field( Option_Model.MAIN_SCREEN_CLICK_FUNC );
		
		boolean Ret = Action_FromString( OptStr );
		
		if( Ret )
			return true;
		else
			return super.navigationClick(status, time);
	}
	

	protected boolean Action_FromString( String OptStr )
	{
		boolean Ret = false;
		
		if( OptStr.equals( "CALL" ) )
		{
	    	if( Call_SelectedNumber() == false )
	    	{
	    		Dialog.alert("Invalid Phone Number"); 
	    		return true;
	    	}
	    	else
	    	{
	    		UiApplication.getUiApplication().requestBackground(); 
	    		return true;
	    	}
		}
		
		if( OptStr.equals( "SMS" ) )
		{
	    	if( SMS_SelectedNumber() == false )
	    	{
	    		Dialog.alert("Invalid Phone Number");    	
	    		return true;
	    	}
	    	else
	    	{
	    		//UiApplication.getUiApplication().requestBackground(); 
	    		return true;
	    	}
		}		

		if( OptStr.equals( "MMS" ) )
		{
	    	if( MMS_SelectedNumber() == false )
	    	{
	    		Dialog.alert("Invalid Phone Number");    	
	    		return true;
	    	}
	    	else
	    	{
	    		//UiApplication.getUiApplication().requestBackground(); 
	    		return true;
	    	}
		}		
		
		if( OptStr.equals( "E-Mail" ) )
		{

			Ret = Popup_SelectedListEmail();

    		return true;
		}		
		
		return Ret;
	}	
  
    //------------------------------------------------------------------------------
    //CLASS : ezCall_Screen
    //
    //WORK : 
    //------------------------------------------------------------------------------   
    private class MenuItem_Call extends MenuItem
    {
    	public MenuItem_Call()
    	{
            super( "Call" , 110, 5);
        }
        
        public void run()
        {
            // If successful display message and close screen.
            {
                //Dialog.alert("Event was saved successfully");
                //onClose();

            	//PhoneArguments call = new PhoneArguments(PhoneArguments.ARG_CALL, phoneNumber);
            	//Invoke.invokeApplication(Invoke.APP_TYPE_PHONE, call);

            	Locale[] _LocaleArray;
            	
            	_LocaleArray = Locale.getAvailableInputLocales();
            	
            	
            	Dialog.alert( Locale.getDefaultInputForSystem().toString() );
            	
            	
            	if( _LocaleArray.length > 0 )
            	{
            		for( int i=0; i<_LocaleArray.length ; i++)
            			Dialog.inform( _LocaleArray[i].toString() );
            	}
            		
            }            
        }           
    }        

    private class MenuItem_About extends MenuItem
    {
    	public MenuItem_About()
    	{
            super( "About" , 120, 5);
        }
        
        public void run()
        {
        	/*
        	if( _Contact_DB.Get_ContactUpdated() )
        	{
        		Dialog.alert( "Updated" );
        	}
        	*/
        	About_PopupScreen _About_PopupScreen = new About_PopupScreen();        	
        	UiApplication.getUiApplication().pushModalScreen( _About_PopupScreen );
        }           
    } 
    
    
    private class MenuItem_Option extends MenuItem
    {
    	
    	public MenuItem_Option()
    	{
            super( "Options" , 121, 5);
        }
        
        public void run()
        {
        	/*
        	if( _Contact_DB.Get_ContactUpdated() )
        	{
        		Dialog.alert( "Updated" );
        	}
        	*/
        	Option_Screen _Option_Screen = new Option_Screen( _Option_Model );        	
        	UiApplication.getUiApplication().pushModalScreen( _Option_Screen );
        	
        	if( _Option_Screen.Get_Updated() == true  )
        	{
                synchronized( _persist ) 
                {
                	_persist.setContents( _Option_Model );
                	_persist.commit();
                	
                }
        	}
        	
            Contact_ListAdjust();
        }           
    }
    
    
    private class MenuItem_ReloadDB extends MenuItem
    {
    	public MenuItem_ReloadDB()
    	{
            super( "Reload DB" , 121, 5);
        }
        
        public void run()
        {
        	//ezCall_Screen.this._Contact_DB.start();
        	
        	ezCall_Screen.this.ReloadDB();
        	
        	//ezCall_Screen.this._Contact_DB.Open_ContactDB();
        	//ezCall_Screen.this._Contact_DB.Reload_ContactDB();
        	
        	//ezCall_Screen.this._Contact_DB.ReloadDB();
        }           
    }     
    private class MenuItem_Close extends MenuItem
    {
    	public MenuItem_Close()
    	{
            super( "Close" , 10000, 5);
        }
        
        public void run()
        {
            close();    
        }           
    }         

    
    
    
	//--------------------------------------------------------------------------
	// 함수 : close
	// 기능 : 
    //       @see net.rim.device.api.ui.Screen#close()
	//--------------------------------------------------------------------------
    public void close()
    {
    	_Contact_DB.Remove_Listener();
    	
    	// 임시로
    	//PersistentStore.destroyPersistentObject( 0x805c524a0059d52dL );
    	
        System.exit(0);        
        super.close();    	
    } 
    
    
    // 취소키누르면  프로그램 백그라운드로
    //
    public boolean onClose()
    {
    	UiApplication.getUiApplication().requestBackground();    	
    	return false;
    }   

    
    
    public boolean Call_SelectedNumber()
    {
    	int SelectedIndex = _Contact_ListField.getSelectedIndex();
    	boolean Ret = false;

    	if( SelectedIndex >= 0 )
    	{
    		Ret = Phone_Lib.Call_ToNumber( _String_SelectedListPhoneNumber );
    		
    		if( Ret == true )
    		{
    			_AfterCalling = true;    	
    			
    			
    			if( _Option_Model.Get_ClearText_AfterCall() )
    			{
    				_ContactList_FindField.setText("");
    				_FindField_Text.Set_Text( "" );
    			}
    		}
    	}
    	
    	return Ret;
    }
    
    public boolean SMS_SelectedNumber()
    {
    	int SelectedIndex = _Contact_ListField.getSelectedIndex();
    	boolean Ret = false;

    	if( SelectedIndex >= 0 )
    	{
    		Ret = Phone_Lib.SMS_ToNumber( _String_SelectedListPhoneNumber );
    		
    		if( Ret == true )
    		{
    			if( _Option_Model.Get_ClearText_AfterCall() )
    			{
    				_ContactList_FindField.setText("");
    				_FindField_Text.Set_Text( "" );
    			}
    		}
    	}
    	
    	return Ret;
    }

    
    public boolean MMS_SelectedNumber()
    {
    	int SelectedIndex = _Contact_ListField.getSelectedIndex();
    	boolean Ret = false;

    	if( SelectedIndex >= 0 )
    	{
    		Ret = Phone_Lib.MMS_ToNumber( _String_SelectedListPhoneNumber );
    		
    		if( Ret == true )
    		{
    			if( _Option_Model.Get_ClearText_AfterCall() )
    			{
    				_ContactList_FindField.setText("");
    				_FindField_Text.Set_Text( "" );
    			}
    		}
    	}
    	
    	return Ret;
    }
    
    public boolean EMAIL_SelectedNumber()
    {
    	int SelectedIndex = _Contact_ListField.getSelectedIndex();
    	boolean Ret = false;

    	if( SelectedIndex >= 0 )
    	{
    		Ret = Phone_Lib.EMAIL_ToAddress( _String_SelectedListPhoneNumber, "" );
    		if( Ret == true )
    		{
    			if( _Option_Model.Get_ClearText_AfterCall() )
    			{
    				_ContactList_FindField.setText("");
    				_FindField_Text.Set_Text( "" );
    			}
    		}
    	}
    	
    	return Ret;
    }    
    
    public BlackBerryContact Get_SelectedContactList()
    {
    	int SelectedIndex = _Contact_ListField.getSelectedIndex();
    	
    	return (BlackBerryContact)_Contact_DB.Get_ItemObjectFromIndex(SelectedIndex);
    }
    
    
    public void Reload_ListFieldSize()
    {
    	_FindField_Text.Set_Text("");
    	_ContactList_FindField.setText("");
    	_Contact_DB.Search( _FindField_Text );
    	_Contact_ListField.setSize(_Contact_DB.Get_MaxSize());
    	_Contact_ListField.invalidate();
    }
   
    
    public EncodedImage getPhoto( BlackBerryContact item ) 
    {
    	
        if (item.countValues(Contact.PHOTO) > 0) 
        {
            try {
            	byte[] photoEncoded = item.getBinary(Contact.PHOTO, 0);
            	byte[] photo = Base64InputStream.decode(photoEncoded, 0, photoEncoded.length);
				
	            EncodedImage image = EncodedImage.createEncodedImage(photo,0,photo.length);
	            
	            return image;

	            
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

        }

        return null;
    }
    
    
    public Bitmap getPhotoBitmap( BlackBerryContact item, int Scale ) 
    {
    	
        if (item.countValues(Contact.PHOTO) > 0) 
        {
            try {
            	byte[] photoEncoded = item.getBinary(Contact.PHOTO, 0);
            	byte[] photo = Base64InputStream.decode(photoEncoded, 0, photoEncoded.length);
				
            	Bitmap image = Bitmap.createBitmapFromBytes(photo, 0, photo.length, Scale);
            	
	            return image;

	            
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

        }

        return null;
    }
    
    public void drawListRow(ListField listField, Graphics graphics, int index, int y, int width) 
    {
    	EncodedImage Contact_Photo;
    	Bitmap Contact_PhotoBitmap;
    	
        if(listField == _Contact_ListField && index < _Contact_DB.Get_MaxSize())
        {

            BlackBerryContact item = (BlackBerryContact)_Contact_DB.Get_ItemObjectFromIndex(index);
            String[] CateArray;
            
            
            int PhotoWidth = 0;
            
            int NameWidth;
            int NamePos;
            int FieldSpace;
            
            int CompanyWidth;
            int CompanyPos;
            int CompanyPosY = 0;
            
            int PhoneNumberWidth;
            int PhoneNumberPos;
            
            
            
        	Font _Font;    	
        	_Font = this.getFont();
            
            if( _Option_Model.Get_Photo_View() )
            {
            	/*
            	FieldSpace = width * 2 / 100;
            	
            	PhotoWidth = width * 10 / 100;
	            NameWidth   = width * 25 / 100;
	            NamePos     = PhotoWidth+FieldSpace;
	            
	            
	            CompanyWidth   = width * 25 / 100;
	            CompanyPos     = NamePos+NameWidth+FieldSpace;
	            CompanyPosY    = _Font.getHeight()+ListRowMargin/2;
	            
	            PhoneNumberWidth   = width * 35 / 100;
	            PhoneNumberPos     = CompanyPos+CompanyWidth+FieldSpace;
	            */
            	FieldSpace = width * 2 / 100;
            	
            	PhotoWidth = width * 10 / 100;
	            NameWidth   = width * 50 / 100;
	            NamePos     = PhotoWidth+FieldSpace;
	            
	            
	            CompanyWidth   = width * 50 / 100;
	            CompanyPos     = width * 40 / 100;
	            CompanyPosY    = _Font.getHeight()+ListRowMargin/2-2;
	            
	            PhoneNumberWidth   = width * 35 / 100;
	            PhoneNumberPos     = width * 62 / 100;
            }
            else
            {
            
	            NameWidth   = width * 30 / 100;
	            NamePos     = 0;
	            FieldSpace = width * 2 / 100;
	            
	            CompanyWidth   = width * 30 / 100;
	            CompanyPos     = NameWidth+FieldSpace;
	            CompanyPosY = 0;
	            
	            PhoneNumberWidth   = width * 35 / 100;
	            PhoneNumberPos     = NameWidth+FieldSpace+CompanyWidth+FieldSpace;
	            
	            

            }
            
            //this.getFont()

            String StrBuf = new String();
            StringBuffer StrOutBuf = new StringBuffer();
            Contact_PhoneNum _Contact_PhoneNum = new Contact_PhoneNum();    
            
            
            
            
            
            // 사진 출력
            //
            
            if( _Option_Model.Get_Photo_View() )
            {
				Contact_Photo = getPhoto( item );
				//Contact_PhotoBitmap = getPhotoBitmap( item, 1 );
				
	            if( Contact_Photo != null )
	            {   
	            	int imgView_Width = PhotoWidth;
	            	int imgView_Height = listField.getRowHeight()-4;
	            	int Scale = 1;
	            	
	            	if( Contact_Photo.getHeight() > Contact_Photo.getWidth() )
	            	{
	            		Scale = Contact_Photo.getHeight()*10000 / imgView_Height;
	            	}
	            	else
	            	{
	            		Scale = Contact_Photo.getWidth()*10000 / imgView_Width;
	            	}
	            	
	            	
	            	EncodedImage Contact_PhotoOut;	
	            	Contact_PhotoOut = Contact_Photo.scaleImage32( Fixed32.tenThouToFP(Scale)  , Fixed32.tenThouToFP(Scale) );
	            	
	            	int ImageView_Y = (listField.getRowHeight()-Contact_PhotoOut.getScaledHeight())/2;
	            	
	            	
	            	//StrOutBuf.append(listField.getRowHeight());
	            	//StrOutBuf.append(" ");
	            	//StrOutBuf.append(ImageView_Y);
	            	
	            	graphics.drawImage(1, y+ImageView_Y-1, Contact_PhotoOut.getScaledWidth(), Contact_PhotoOut.getScaledHeight(), Contact_PhotoOut, 0, 0, 0);	            		            	
	            }
            }            
            
            
            
            int ContactFieldCount;
            
            ContactFieldCount = item.countValues(Contact.NAME);
            
            if( ContactFieldCount > 0 )
            {
	            String[] NameArray = item.getStringArray(Contact.NAME, 0);
	
	            // 이름 표시 순서 결정
	            //
	            switch( _Option_Model.Get_Order_NameView() )
	            {
	            case Option_Model.NAME_VIEW_LAST_NAME_FIRST:
	            	if((StrBuf = NameArray[Contact.NAME_FAMILY]) != null)
	            	{
	            		StrOutBuf.append(StrBuf);
	            		
	            		if( _Option_Model.Get_Space_BetweenLastFirstName() )
		            		StrOutBuf.append(" ");
	            	}
	            	
	 	            if((StrBuf = NameArray[Contact.NAME_GIVEN]) != null)
	 	            		StrOutBuf.append(StrBuf);
	 	            break;
	 	            
	            case Option_Model.NAME_VIEW_FIRST_NAME_FIRST:
	            	if((StrBuf = NameArray[Contact.NAME_GIVEN]) != null)
	            	{
	            		StrOutBuf.append(StrBuf);
	            	
	            		if( _Option_Model.Get_Space_BetweenLastFirstName() )
	            			StrOutBuf.append(" ");
	            	}
	            	
		 	       	if((StrBuf = NameArray[Contact.NAME_FAMILY]) != null)
		 	       			StrOutBuf.append(StrBuf);
	            	break;
	            }
            }
            
            
            String JobTitle = new String();
            
            // 직책 출력
            if( item.countValues( Contact.TITLE ) > 0 )
            {
            	if( _Option_Model.Get_Photo_View() )
            	{
            		JobTitle = StrBuf = item.getString(Contact.TITLE, 0);
            	}
            	else
            	{
	            	StrOutBuf.append(" ");
	            	StrBuf = item.getString(Contact.TITLE, 0);
	            	StrOutBuf.append(StrBuf);
            	}
            }
            if( StrOutBuf.length() > 0 )
            	StrBuf = StrOutBuf.toString();
            else
            	StrBuf = " ";
            

        	
        	Font _Namefont = graphics.getFont().derive( Font.BOLD );        	
        	graphics.setFont( _Namefont );        	
            graphics.drawText(StrBuf, NamePos, y + ListRowMargin/2, Graphics.ELLIPSIS, NameWidth);
            graphics.setFont( _Font );
            

            
            
            // 카테고리 Load
        	CateArray = item.getCategories();
        	
            // 회사 출력
            if( item.countValues( Contact.ORG ) > 0 )
            {
            	
            	Font _font = graphics.getFont().derive( Font.PLAIN, _Font.getHeight()*8/10 );
            	
            	String CompanyName = item.getString(Contact.ORG, 0);
            	graphics.setFont( _font );
            	graphics.drawText(CompanyName, CompanyPos, y + CompanyPosY+ ListRowMargin/2 + _Font.getHeight()*1/10, Graphics.ELLIPSIS, CompanyWidth);
            	graphics.setFont( _Font );
            	
            	String TitleInfoStr = new String();
            	            	
            	TitleInfoStr = " ";
            	
            	// 만약 선택된 리스트이면
            	if( listField.getSelectedIndex() == index )
            	{            		
	            	// 화면 상단에 카테고리 출력            	
	            	if( CateArray.length > 0 )
	            	{
	            		//_ContactList_FindField.Set_TitleInforStr( "("+CateArray[0]+")" );
	            		//TitleInfoStr = "("+CateArray[0]+")";
	            		//_TitleInfo_LabelField.setText( TitleInfoStr, 0, TitleInfoStr.length() );
	            		TitleInfoStr = "("+CateArray[0]+")";
	            		
	            		_Top_Str = TitleInfoStr;
	            		
	                    UiApplication.getUiApplication().invokeLater(new Runnable() 
	                    {
	                        public void run() 
	                        {
	                        	_TitleInfo_LabelField.setText( _Top_Str );
	                        }
	                    });
	            		
	            		
	            	}
            	}            	
            }
            else
            {
            	//_TitleInfo_LabelField.setText("");
        		/*
                UiApplication.getUiApplication().invokeLater(new Runnable() 
                {
                    public void run() 
                    {
                    	_TitleInfo_LabelField.setText("");
                    }
                });
            	*/
            	
            	
            	if( listField.getSelectedIndex() == index )
            	{
                    UiApplication.getUiApplication().invokeLater(new Runnable() 
                    {
                        public void run() 
                        {
                        	_TitleInfo_LabelField.setText("");
                        }
                    });	
            	}
            	
            	
            	// 회사가 없으면 카테고리 출력
            	if( CateArray.length > 0 )
            	{
                	Font _font = graphics.getFont().derive( Font.PLAIN, _Font.getHeight()*8/10 );
                	graphics.setFont( _font );
            		graphics.drawText( "("+CateArray[0]+")", CompanyPos, y + CompanyPosY+ListRowMargin/2+_Font.getHeight()*1/10, Graphics.ELLIPSIS, CompanyWidth);
            		graphics.setFont( _Font );
            	}
            }
            
            
            // 메모 검색일때는 메모를 출력
            //
            if( _FindField_Text.Get_FindMode() == FindField_Text.FIND_MODE_NOTE )
            {
            	
            	if( item.countValues( Contact.NOTE ) > 0 )
            	{
            		graphics.drawText( item.getString( Contact.NOTE, 0), PhoneNumberPos, y + ListRowMargin/2, Graphics.ELLIPSIS, PhoneNumberWidth);
            	}
            	return;
            }
            
            
            
            // 전화번호 출력
            _Contact_PhoneNum.Set_Contact(item);
            
            
            if( _Contact_PhoneNum.Get_PhoneNumberCount() > 0 )
            {
            	if( _FindField_Text.Get_FindMode() ==  FindField_Text.FIND_MODE_PHONE_NUMBER )
            	{
            		graphics.drawText(_Contact_DB.Get_MatchedPhoneNumberStr(item, index), PhoneNumberPos, y + ListRowMargin/2, Graphics.ELLIPSIS, PhoneNumberWidth);
            		
            		if( listField.getSelectedIndex() == index )
            			_String_SelectedListPhoneNumber = _Contact_DB.Get_MatchedPhoneNumberStr(item, index);
            	}
            	else
            	{
            		graphics.drawText(_Contact_PhoneNum.Get_FirstPhoneNumber(), PhoneNumberPos, y + ListRowMargin/2, Graphics.ELLIPSIS, PhoneNumberWidth);
            		if( listField.getSelectedIndex() == index )
            			_String_SelectedListPhoneNumber = _Contact_PhoneNum.Get_FirstPhoneNumber();
            	}
            }
            else
            {
        		if( listField.getSelectedIndex() == index )
        			_String_SelectedListPhoneNumber = "";            	
            }
            
            
            if( _Option_Model.Get_Photo_View() )
            {
            	
            	Font _font = graphics.getFont().derive( Font.PLAIN, _Font.getHeight()*7/10 );
            	
            	graphics.setFont(_font);
            	graphics.drawText(JobTitle, NamePos+10, y +_Font.getHeight()+ ListRowMargin + _Font.getHeight()*2/10, Graphics.ELLIPSIS, NameWidth+CompanyWidth);

            	graphics.setColor(0x00E0E0E0);
            	graphics.drawLine(0, y+listField.getRowHeight()-1, graphics.getScreenWidth(), y+listField.getRowHeight()-1);
            }
            
        }
        

    }

    

    public Object get(ListField listField, int index)
    {
        
    	if(  _Contact_DB.Get_MaxSize() <= index ) return null;
    	
    	return _Contact_DB.Get_ItemObjectFromIndex( index );
    
    }
    

    public int getPreferredWidth(ListField listField) 
    {
    	return Graphics.getScreenWidth();
    }
 
   
    public int indexOfList(ListField listField, String prefix, int start) 
    {
        return -1; // Not implemented.
    }    
    
    
    public void onExposed()
    {
    	
    	if( _AfterCalling )
    	{
    		Locale.setDefaultInput(null);
    		//Locale.setDefaultInputForSystem(Locale.getDefaultInputForSystem());
    		Locale.setDefaultInput( Locale.getDefaultInputForSystem());
    		//Locale.setDefault(null);  // 디폴트 값을 가진다.
    		
    		_AfterCalling = false;
    	}
    	
    	
    	if( _Contact_DB.Get_ContactUpdated() )
    	{
    		_Contact_DB.Clear_ContactUpdated();
    		
    		Reload_ListFieldSize();
    	}
    	super.onExposed();
    }
        
}
